import re

from flask import request, current_app, url_for,redirect,g

from application import app
from common.libs.UserSerivice import UserService
from web.models.user import User
from common.libs.logservice import LogService


def check_login():
    """判断用户是否登录"""
    # 使用cookie 来验证是否登录
    cookie = request.cookies
    auth_key = current_app.config["AUTH_COOKIE_NAME"]
    auth_cookie = cookie[auth_key] if auth_key in cookie else ""
    # print(auth_cookie) #7d267998aa49e9c8a130f6a6b23763dc#1
    if auth_cookie is None:
        return False  # False表示没有登录
    # food:  bdc556da52d17c3f664aa50c1d1c77cc#1
    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False
    try:
        user_info = User.query.filter_by(uid=auth_info[1]).first()
    except:
        return False
    if user_info is None:
        return False
    # 判断密钥
    authcode = UserService.genAuthCode(user_info)
    if auth_info[0] != authcode:
        return False
    # 用户已合法登录
    return user_info

@app.before_request
def before_request_():
    """拦截器"""
    path = request.path
    user_info = check_login()  # 登录校验，返回用户对象
    # 把用户信息写入g对象
    g.current_user=user_info

    # 取得忽略的路径(登录、静态资源、小程序端(/api)的请求)
    ignore_urls = current_app.config["IGNORE_URLS"]
    api_ignore_urls = current_app.config["API_IGNORE_URLS"]
    ignore_check_login_urls = current_app.config["IGNORE_CHECK_LOGIN_URLS"]
    ignore_merge = ignore_urls + ignore_check_login_urls +api_ignore_urls # 所有的忽略的url
    print('过滤的路由：', ignore_merge)
    # 正则表达式 编译规则
    pattern = re.compile("|".join(ignore_merge))
    if pattern.match(path):
        return None  # return None不做拦截
    if not user_info:  # 没有登录
        # 重定向到登录页面
        return redirect(url_for('user_page.login'))

    # 把访问信息写入到日志表中
    LogService.addAccesslog()
    return None  # return None不做拦截

